package org.javadatabasemigrations.util;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import sun.misc.Launcher;


public class PackageUtils {

    public static List<Class> classesInPackage(final String packageName)
        throws ClassNotFoundException {

        File directory = directoryFromPackageName(packageName);
        if (!directory.exists()) {
            return null;
        }

        String[] files = directory.list();
        List<Class> classesInPackage = classesFromFileNames(packageName, files);
        return classesInPackage;
    }


    private static List<Class> classesFromFileNames(final String packageName,
                                                    final String[] files)
        throws ClassNotFoundException {

        List<Class> classesInPackage = new ArrayList<Class>();
        for (int i = 0; i < files.length; i++) {

            if (!files[i].endsWith(".class")) {
                continue;
            }
            String className = classNameFromFileName(files[i]);
            String qualifiedName = packageName + "." + className;
            Class clazz = Class.forName(qualifiedName);
            classesInPackage.add(clazz);
        }
        return classesInPackage;
    }


    private static File directoryFromPackageName(final String packageName) {

        String directoryName = packageName;
        if (!directoryName.startsWith("/")) {
            directoryName = "/" + directoryName;
        }
        directoryName = directoryName.replace('.', '/');

        URL url = Launcher.class.getResource(directoryName);
        File directory = new File(url.getFile());
        return directory;
    }


    private static String classNameFromFileName(final String file) {

        return file.substring(0, file.length() - 6);
    }

}
